package com.gitee.sparta.common.helpers;

import cn.hutool.core.date.DateUtil;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 时间工具
 *
 * @author zyred
 * @since v 0.0.1
 */
public class DurationHelper {

    public static final String DEFAULT_FORMATTER = "yyyy-MM-dd HH:mm:ss";
    public static final String NANO_FORMATTER = DEFAULT_FORMATTER + ":SSS";

    public static Long[] timestamp (List<String> times) {
        Long[] timestamps = new Long[times.size()];
        for (int i = 0; i < times.size(); i++) {
            timestamps[i] = timestamp(times.get(i));
        }
        return timestamps;
    }

    /**
     * 将字符串转换为时间戳，13位
     *
     * @param time      yyyy-MM-dd HH:mm:ss
     * @return          13 位时间戳
     */
    public static long timestamp (String time) {
        // 获取当前纳秒， 3位
        int nano = LocalDateTime.now().getNano() / 1000000;
        // 组装上纳秒
        time = time + ":" + nano;
        // yyyy-MM-dd HH:mm:ss:SSS
        LocalDateTime localDateTime = DateUtil.parseLocalDateTime(time, NANO_FORMATTER);
        return localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
    }


    public static Set<Long> parseMillis (Collection<Duration> durations) {
        List<Long> arr = new LinkedList<>();
        for (Duration duration : durations) {
            arr.add(System.currentTimeMillis() + parseMillis(duration));
        }
        return arr.stream().sorted(Long::compareTo).collect(Collectors.toCollection(LinkedHashSet::new));
    }

    public static long parseMillis (Duration duration) {
        return duration.getSeconds() * 1_000L;
    }

    /**
     * 将字符串解析为 Duration 对象
     *
     * @param texts     满足 Duration 对象格式的要求
     *                  不过此处主要是解析间隔时间，并非完整时间格式
     *                  例如：[PT1S, PT2S,PT3S, ...]
     * @return          时间格式 Duration 对象
     */
    public static Set<Duration> parseDuration (Set<String> texts) {
        Set<Duration> durations = new LinkedHashSet<>();
        for (String text : texts) {
            durations.add(Duration.parse(text));
        }
        return durations;
    }
}
